package com.cy.store.controller;


import com.cy.store.entity.Favor;
import com.cy.store.service.ICartService;
import com.cy.store.service.IFavorService;
import com.cy.store.util.JsonResult;
import com.cy.store.vo.CartVO;
import com.cy.store.vo.FavorVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("favors")
public class FavorController extends BaseController{

    @Autowired
    private IFavorService favorService;

    @RequestMapping("add_to_favor")
    public JsonResult<Void> addToFavor(Integer pid,  HttpSession session) {
        System.out.println("pid=" + pid);
        // 从Session中获取uid和username
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        // 调用业务对象执行添加到购物车
        favorService.addToFavor(uid, pid, username);
        // 返回成功
        return new JsonResult<Void>(OK);
    }

    @RequestMapping("{fid}/delFavorItem")
    public JsonResult<Void> delFavorItem(@PathVariable("fid") Integer fid, HttpSession session) {
        System.out.println("进入取消收藏fid"+fid);
        // 从Session中获取uid和username
        Integer uid = getUidFromSession(session);
        System.out.println("进入取消收藏uid"+uid);
        // 调用业务对象执行添加到购物车
        favorService.delFavorItem(fid,uid);//相当于工具类来调用每一个功能的具体代码
        // 返回成功
        return new JsonResult<Void>(OK);
    }

    @GetMapping({"", "/"})
    public JsonResult<List<FavorVO>> getVOByUid(HttpSession session) {
        // 从Session中获取uid
        Integer uid = getUidFromSession(session);
        // 调用业务对象执行查询数据
        List<FavorVO> data = favorService.getVOByUid(uid);
        // 返回成功与数据
        return new JsonResult<List<FavorVO>>(OK, data);
    }

    @RequestMapping("{pid}/judgeExist")
    public JsonResult<Favor> judgeExist(@PathVariable("pid") Integer pid, HttpSession session) {
        // 从Session中获取uid和username
        Integer uid = getUidFromSession(session);
        // 调用业务对象执行添加到购物车
        Favor data=favorService.judgeExist(pid,uid);//相当于工具类来调用每一个功能的具体代码
//        System.out.println("控制层"+data);
        // 返回结果集给前端ajax
        if (data==null){
            return new JsonResult<>(NO);
        }else {
            return new JsonResult<Favor>(OK,data);
        }

    }
}
